#!/bin/bash
lst_file=$1
dst_root=$2
version=${3:-v0.7}
need_pack=${4:-y}
use_xz=${5:-n}
debug=${5:-n}

if [ -e $lst_file ]; then
    file_ctn=$(cat $lst_file)
else
    echo "Invalid list file!"
    exit -1
fi

[ -e $dst_root ] || mkdir -p $dst_root

# softlinks
softlinks=$(sed -n '/^\[softlinks\]/,/\[\\softlinks\]$/p' $lst_file | grep -Ev '(^\[softlinks\]|\[\\softlinks\]$)' | cut -f 1,2)
for softlink in $softlinks
do
    echo "Softlink: $softlink"
    cp -d --parents $softlink $dst_root
done


# commands
commands=$(sed -n '/^\[commands\]/,/\[\\commands\]$/p' $lst_file | grep -Ev '(^\[commands\]|\[\\commands\]$)' | cut -f 1,2)
for cmd in $commands
do
    echo "Command: $cmd"
    cpc $cmd $dst_root
done

if [[ "$debug" == "y" ]]
then
    cpc strace $dst_root
fi

modules_meta=/lib/modules/$(uname -r)/modules.*
cp --parents $modules_meta $dst_root

# modules
modules=$(sed -n '/^\[modules\]/,/\[\\modules\]$/p' $lst_file | grep -Ev '(^\[modules\]|\[\\modules\]$)' | cut -f 1,2)
for module in $modules
do
    echo "Module: $module"
    cpko $module $dst_root
done



# files
files=$(sed -n '/^\[files\]/,/\[\\files\]$/p' $lst_file | grep -Ev '(^\[files\]|\[\\files\]$)' | cut -f 1,2)
for file_re in $files
do
    # if absolute path, find will unfold simple regular expression and folders
    file_list=`find $file_re -prune`
    for file in $file_list
    do
        if [ -d $file ]
        then 
            echo -n "Directory: "
        else
            echo -n "File: "
        fi
        echo $file
        # recursively copy files to cover directories
        cp -r --parents $file $dst_root
    done
done

cp ~/inits/init-$version $dst_root/init

if [[ "$need_pack" == "y" ]]; then
    cd $dst_root
    if [[ "$use_xz" == "y" ]]
    then
        find . | cpio -H newc -o | xz --check=crc32 > /boot/initrd-minifs.img
    else
        find . | cpio -H newc -o | gzip > /boot/initrd-minifs.img
    fi
fi
